<template>
  <el-dialog
    :title="isEdit ? '编辑客户' : '新增客户'"
    v-model="dialogVisible"
    width="800px"
    destroy-on-close
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户编码" prop="customerCode">
            <el-input
              v-model="form.customerCode"
              placeholder="请输入客户编码"
              :disabled="isEdit"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="form.customerName" placeholder="请输入客户名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户简称" prop="shortName">
            <el-input v-model="form.shortName" placeholder="请输入客户简称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户类型" prop="customerType">
            <el-select v-model="form.customerType" placeholder="请选择客户类型" style="width: 100%">
              <el-option label="U8" value="U8" />
              <el-option label="电池箔" value="BATTERY" />
              <el-option label="铜铝复合" value="COPPER_ALUMINUM" />
              <el-option label="纯铝" value="PURE_ALUMINUM" />
              <el-option label="再生铝" value="RECYCLED_ALUMINUM" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="负责人" prop="responsiblePerson">
            <el-input v-model="form.responsiblePerson" placeholder="请输入负责人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人电话" prop="responsiblePhone">
            <el-input v-model="form.responsiblePhone" placeholder="请输入负责人电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="负责人邮箱" prop="responsibleEmail">
            <el-input v-model="form.responsibleEmail" placeholder="请输入负责人邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择客户状态" style="width: 100%">
              <el-option label="售前" value="pre-sales" />
              <el-option label="正常" value="normal" />
              <el-option label="注销" value="deleted" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入地址" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useCustomerStore } from '../../../store/customer.js'

export default {
  name: 'CustomerEditDialog',
  props: {
    modelValue: Boolean,
    customer: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    // 使用客户Store
    const customerStore = useCustomerStore()
    
    const formRef = ref(null)
    const loading = ref(false)
    
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })
    
    const isEdit = computed(() => !!props.customer?.id)

    // 表单数据
    const form = reactive({
      customerCode: '',
      customerName: '',
      shortName: '',
      customerType: '',
      responsiblePerson: '',
      responsiblePhone: '',
      responsibleEmail: '',
      address: '',
      status: 'normal',
      remark: ''
    })

    // 表单验证规则
    const rules = reactive({
      customerCode: [
        { required: true, message: '请输入客户编码', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      customerName: [
        { required: true, message: '请输入客户名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      shortName: [
        { required: true, message: '请输入客户简称', trigger: 'blur' },
        { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
      ],
      customerType: [
        { required: true, message: '请选择客户类型', trigger: 'change' }
      ],
      responsiblePerson: [
        { required: true, message: '请输入负责人', trigger: 'blur' }
      ],
      responsiblePhone: [
        { required: true, message: '请输入负责人电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      responsibleEmail: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择客户状态', trigger: 'change' }
      ]
    })

    // 初始化表单数据
    const initFormData = () => {
      if (props.customer) {
        Object.assign(form, props.customer)
      } else {
        Object.assign(form, {
          customerCode: '',
          customerName: '',
          shortName: '',
          customerType: '',
          responsiblePerson: '',
          responsiblePhone: '',
          responsibleEmail: '',
          address: '',
          status: 'normal',
          remark: ''
        })
      }
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            if (isEdit.value) {
              // 编辑客户
              await customerStore.updateCustomer(props.customer.id, {
                customerName: form.customerName,
                shortName: form.shortName,
                customerType: form.customerType,
                responsiblePerson: form.responsiblePerson,
                responsiblePhone: form.responsiblePhone,
                responsibleEmail: form.responsibleEmail,
                address: form.address,
                status: form.status,
                remark: form.remark
              })
              ElMessage.success('客户更新成功')
            } else {
              // 创建客户
              await customerStore.createCustomer({
                customerCode: form.customerCode,
                customerName: form.customerName,
                shortName: form.shortName,
                customerType: form.customerType,
                responsiblePerson: form.responsiblePerson,
                responsiblePhone: form.responsiblePhone,
                responsibleEmail: form.responsibleEmail,
                address: form.address,
                status: form.status,
                remark: form.remark
              })
              ElMessage.success('客户创建成功')
            }
            emit('success')
            dialogVisible.value = false
          } catch (error) {
            console.error('保存客户失败:', error)
            ElMessage.error('保存客户失败')
          } finally {
            loading.value = false
          }
        }
      })
    }

    // 对话框关闭
    const handleClosed = () => {
      formRef.value?.resetFields()
    }

    // 监听对话框显示状态
    watch(() => props.modelValue, (val) => {
      if (val) {
        initFormData()
      }
    })

    return {
      formRef,
      loading,
      dialogVisible,
      isEdit,
      form,
      rules,
      handleSubmit,
      handleClosed
    }
  }
}
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>